package cn.xorange.commons.security.service;

import cn.xorange.commons.security.configuration.SecurityProperties;
import cn.xorange.commons.security.entity.LoginLog;
import cn.xorange.commons.security.entity.SecurityUser;
import cn.xorange.commons.security.enums.SysType;
import cn.xorange.commons.security.mapper.LogMapper;
import cn.xorange.commons.utils.spring.SpringUtils;
import com.alibaba.fastjson2.JSONObject;

import java.util.Objects;
import java.util.TimerTask;

/**
 * @author : yangjian
 * @date : 2023/11/25
 */
public interface LoginHandler {


    default String getLoginSysAndType(){
        return this.config().getSysType() + ":" + this.config().getLoginType();
    }

    SecurityProperties config();

    SecurityUser handle(JSONObject object);

    default TimerTask setLog(String loginName, SecurityUser user, Integer status, String msg){
        String sysType = this.config().getSysType();
        LoginLog log = new LoginLog(loginName,this.config().getLoginType(),status,msg);
        if(Objects.nonNull(user)){
            log.setTenantId(user.getTenantId());
            log.setTenantName(user.getTenantName());
            log.setUserId(user.getUserId());
            log.setUserName(user.getUsername());
        }

        return new TimerTask() {
            @Override
            public void run() {
                LogMapper logMapper = SpringUtils.getBean(LogMapper.class);
                if(SysType.SYS.type().equals(sysType)){
                    logMapper.insertSysLoginLog(log);
                }else if(SysType.APP.type().equals(sysType)){
                    logMapper.insertAppLoginLog(log);
                }
            }
        };
    }

}
